<?php

namespace app\erp\controller;

use app\erp\model\SdInvoiceLogdb;
use app\erp\model\UOrderdb;
use think\Controller;
use GuzzleHttp\Client;
use app\erp\model\Orderdb;
use app\erp\model\Cartdb;
use app\erp\model\Goodsdb;
use app\erp\model\Invoicedb;
use app\api\model\Postdatadb;
use think\Db;
use app\erp\model\Uploaddb;
use think\Cache;

class Invoiceapi extends Controller
{
    private $appid = 'fc10bacd8b2a56bcbc568121ef5f1b51'; // 开放平台申请
    private $appSecret = '8ac4a659990dca0d87a9a0a005817246f58a155b'; // 开放平台申请
    protected $baseUrl = 'https://paymgmt.shuzutech.com/invoice/';
//正式环境
    protected $shuihao = '91110105675715354X';
    protected $bianhao = '667003824772';
    //   protected $kaipiaoren = '陈阳';
    //  protected $dizhi = '北京市朝阳区管庄乡杨闸村京通辅路南8号院F1 01059521909';
    //  protected $yinhang = '交通银行北京林萃路支行 110061203018010014524';
//测试环境
    //  protected $shuihao = '50010215010418661';
    // protected $bianhao = '661015451523';
    //   protected $kaipiaoren = '测试开票';
    //  protected $dizhi = '金蝶软件园 0755-86071517';
    //  protected $yinhang = '招商银行高新园支行 123456';

    /*
     * 数电发票信息(正式)
     * 测试地址：https://paymgmt.dev.shuzutech.com
     * 正式地址：https://paymgmt.shuzutech.com
     */
    protected $sd = [
        'nsrsbh' => '91110105675715354X',
        'dlzh' => '18613310595',
        'APPID' => 'fc10bacd8b2a56bcbc568121ef5f1b51',
        'APPSCRT' => '8ac4a659990dca0d87a9a0a005817246f58a155b',
        'api_url' => 'https://paymgmt.shuzutech.com',
        'token_url' => 'https://dev.zhenpos.com'
    ];

    /*
     * 数电发票信息(测试) 333444 
     * 测试地址：https://paymgmt.dev.shuzutech.com
     * 正式地址：https://paymgmt.shuzutech.com
     */
    protected $sd_test = [
        'nsrsbh' => '91110105675715354X',
        'dlzh' => 'tailongji',
        'APPID' => 'a2a59a8a5ef5a204a714932e71d626af',
        'APPSCRT' => 'a418d6b4d9607aa15476405cf119e96e726e01bb',
        'api_url' => 'https://paymgmt.dev.shuzutech.com',
        'token_url' => 'http://openplat.dev.shuzutech.com'
    ];


    public function _initialize()
    {
        define('MEMBER_ID', 1);
        define('SITE_ID', 117);
        define('PARTNER_ID', 25);
        // 将配置文件的字段名dlzh修改成后台配置的财务手机号
        $this->sd['dlzh'] = getSiteConfig('CW_PHONE');
    }


    /**
     * 获取数电token
     */
    public function getSdToken()
    {
        $url = $this->sd['token_url'] . "/openplat/dev/refreshAccessToken?";
        $parm = "appId=" . $this->sd['APPID'] . "&appScrt=" . $this->sd['APPSCRT'];
        $content = @file_get_contents($url . $parm);
        $json_data = json_decode($content, true);
        return $json_data['result']['accessToken'];
    }

    /**
     * 开具数电蓝票
     */
    public function sdMakeInvoice($order_no)
    {
        $serviceId = 'FPKJ';
        $api = '/invoiceEx/zpy/electric/invoice/issued';
        $get_order = Db::name('order')->where('order_no', $order_no)->field('order_no,out_order_no,order_money')->find();
        if (!$get_order) {
            $this->layuiReturn('订单信息错误', 0);
        }
        $get_invoice = Db::name('invoice')->where('order_nos', $order_no)->field('invoice_id,invoice_beizhu,api_bianhao,invoice_duty,invoice_title,invoice_addr,invoice_tel,invoice_bank,invoice_account')->find();
        if (!$get_invoice) {
            $this->layuiReturn('发票信息错误', 0);
        }
        $get_cart = Db::name('cart')->alias('c')->join('goods g', 'g.goods_sku=c.goods_sku')->where('c.order_no', $order_no)
            ->field('c.goods_sku,c.goods_sale_price goods_price,c.goods_num,g.goods_name,c.goods_keywords cart_se,g.goods_keywords goods_se,c.invoice_model,g.goods_model,c.goods_unit cart_goods_unit,
            g.goods_unit,c.shuiwu_id cart_shuiwu_id,g.shuiwu_id goods_shuiwu_id,c.product_firm cart_product_firm,g.product_firm')
            ->select();
        if ($get_cart->isEmpty()) {
            $this->layuiReturn('订单商品错误', 0);
        }
        $content = [];
        //$content ['sync'] = false;
        $content ['zsxfyh'] = 1;
        $content ['bz'] = '联行号：309100003253 ' . ($get_invoice ['invoice_beizhu'] ?: '');
        $content ['fplxdm'] = 82;


        $content ['fpqqlsh'] = $get_invoice['api_bianhao'] ? $get_invoice['api_bianhao'] : $get_order ['out_order_no'] . '_' . date('YmdHi');
        // 购方信息
        $content ['gfmc'] = $get_invoice['invoice_title'];
        $content ['gfsh'] = $get_invoice['invoice_duty'] ?: '';
        $content ['gfdz'] = $get_invoice ['invoice_addr'] ?: '';
        $content ['gflxdh'] = $get_invoice ['invoice_tel'] ?: '';
        $content ['gfkhh'] = $get_invoice ['invoice_bank'] . ' ' . $get_invoice ['invoice_account'];
        // 销方信息
        $content ['xfdz'] = '北京市朝阳区管庄乡杨闸村京通辅路南8号院F1';
        $content ['xfkhh'] = '兴业银行股份有限公司北京月坛支行';
        $content ['xflxdh'] = '010-87954452';
        $content ['xfmc'] = '北京市泰龙吉贸易有限公司';
        $content ['xfyhzh'] = '321150100100195996';
        $content ['kcje'] = '0.00';
        $content ['kprq'] = date('Ymd');
        $content ['pzhjje'] = number_format($get_order['order_money'] / 100, 2, '.', '');
        $content ['pzlx'] = 1;
        $content ['hsbz'] = 1; // 1=含税 0=不含税
        $content ['mxList'] = [];
        $content ['gfxxqr'] = "0";
        $content ['spExt']['hddz'] = "https://tailongji.dixintong.com/erp/invoiceapi/sdcallback/service_id/FPKJBC/order_no/" . $order_no . ".html";
        foreach ($get_cart as $key => $val) {
            $temp = [];
            $temp['fphxz'] = "0";
            //$temp['ggxh'] = str_replace('/', '', ($val['invoice_model'] ?: $val['goods_model']));
            $temp['ggxh'] = $val['invoice_model'] ?: $val['goods_model'];
            $temp ['sl'] = $val['cart_se'] ?: $val['goods_se']; // 税率
            $temp ['dj'] = $val['goods_price'];// 单价
            $temp ['je'] = $val['goods_price'] * $val['goods_num']; // 金额
            $temp ['se'] = number_format(($temp ['je'] - $temp ['je'] / (1 + $temp['sl'])), 2, '.', '');

            /*$temp ['hsze'] = number_format($val ['goods_price'] * $val ['goods_num'],2,'.','');
            $je = $temp ['hsze'] / (1 + $temp ['sl']);
            $temp ['je'] = number_format($je, 2, '.', ''); // 总价
            $temp ['se'] = number_format(($temp ['hsze'] - $je), 2, '.', '');//税额
            $temp ['dj'] = number_format($je / $val ['goods_num'],2,'.',''); // 单价*/
            //$temp ['spmc'] = str_replace('/', '', $val['cart_product_firm'] ?: $val['product_firm']);
            $temp ['spmc'] = $val['cart_product_firm'] ?: $val['product_firm'];
            $temp ['spbm'] = $val['cart_shuiwu_id'] ?: $val['goods_shuiwu_id'];
            $temp ['spsl'] = $val['goods_num'];
            $temp ['dw'] = $val['cart_goods_unit'] ?: $val['goods_unit'];
            array_push($content['mxList'], $temp);
        }
        $content ['tdyslxdm'] = "";
        $content['nsrsbh'] = $this->sd['nsrsbh'];
        $result = $this->sdsend($api, $serviceId, $content, $order_no);
        if ($result['code'] == '0') {
            // 成功
            $uploaddb = new Uploaddb ();
            $uploaddb->param ['save_path'] = $result['content']['pdfUrl'];
            $uploaddb->param ['file_name'] = time() . '.pdf';
            $uploaddb->param ['is_outlink'] = 2;
            $uploaddb->param ['type'] = 'pdf';
            $uploaddb->param ['size'] = 100;
            $get_upload = $uploaddb->ajaxSave();

            $invoice_data ['state'] = 2;

            $invoice_data ['api_bianhao'] = $content ['fpqqlsh'];
            $invoice_data ['api_type'] = 82;
            $invoice_data ['api_date'] = date('Y-m', time());
            $invoice_data ['api_return_no'] = $content ['fpqqlsh'];
            $invoice_data ['fapiaohao'] = $result['content']['fphm'];
            $invoice_data ['fapiaodaima'] = $result['content']['fphm'];
            $invoice_data ['state'] = 2;
            $invoice_data ['invoice_time'] = time();
            $invoice_data ['invoice_proof'] = $get_upload ['upload_id'];
            $invoice_data ['shuie'] = $result['content']['hjse'];
            $invoice_data ['kprq'] = $result['content']['kprq'];
            $invoicedb = new Invoicedb();
            $invoicedb->useGlobalScope(false)->where('invoice_id', $get_invoice ['invoice_id'])->update($invoice_data);
            $orderdb = new Orderdb ();
            $orderdb->useGlobalScope(false)->where('order_no', $get_order['order_no'])->update([
                'returncode' => '成功'
            ]);

            $UOrderdb = new UOrderdb();
            $UOrderdb->param['order_no'] = $get_order['order_no'];
            $UOrderdb->param['invoice_data'] = $invoice_data;
            $UOrderdb->setInvoice();
            $this->layuiReturn($result['msg'], 1);

        } else {
            $this->layuiReturn('失败，错误码：' . $result['msg'], 0);
        }
    }

    /**
     * Title("数电回调地址")
     */
    public function sdcallback()
    {
        session('member_id', 1);
        $log_data = [];
        $log_data['order_no'] = request()->param('order_no');
        $log_data['service_id'] = request()->param('service_id');
        $log_data['api'] = 'sdcallback';
        $log_data['result'] = json_encode(request()->param());
        $log_data['api_date'] = date('Y-m-d H:i:s');
        $logdb = new SdInvoiceLogdb();
        $logdb->save($log_data);
        $result = json_decode($log_data['result'], true);
        if ($result['code'] == '0') {
            if ($log_data['service_id'] == 'FPKJBC') {
                $get_order = Db::name('order')->where('order_no', $log_data['order_no'])->field('order_no,returncode')->find();
                if ($get_order['returncode'] != '成功') {
                    $get_invoice = Db::name('invoice')->where('order_nos', $get_order['order_no'])->field('invoice_id')->find();
                    $uploaddb = new Uploaddb ();
                    $uploaddb->param ['save_path'] = $result['content']['pdfUrl'];
                    $uploaddb->param ['file_name'] = time() . '.pdf';
                    $uploaddb->param ['is_outlink'] = 2;
                    $uploaddb->param ['type'] = 'pdf';
                    $uploaddb->param ['size'] = 100;
                    $get_upload = $uploaddb->ajaxSave();

                    $invoice_data ['state'] = 2;


                    $invoice_data ['api_bianhao'] = $result['content'] ['fpqqlsh'];
                    $invoice_data ['api_type'] = 82;
                    $invoice_data ['api_date'] = date('Y-m', time());
                    $invoice_data ['api_return_no'] = $result['content'] ['fpqqlsh'];
                    $invoice_data ['fapiaohao'] = $result['content']['fphm'];
                    $invoice_data ['fapiaodaima'] = $result['content']['fphm'];
                    $invoice_data ['state'] = 2;
                    $invoice_data ['invoice_time'] = time();
                    $invoice_data ['invoice_proof'] = $get_upload ['upload_id'];
                    $invoice_data ['shuie'] = $result['content']['hjse'];
                    $invoice_data ['kprq'] = $result['content']['kprq'];
                    $invoicedb = new Invoicedb();
                    $invoicedb->useGlobalScope(false)->where('invoice_id', $get_invoice ['invoice_id'])->update($invoice_data);
                    $orderdb = new Orderdb ();
                    $orderdb->useGlobalScope(false)->where('order_no', $get_order['order_no'])->update([
                        'returncode' => '成功'
                    ]);

                    $UOrderdb = new UOrderdb();
                    $UOrderdb->param['order_no'] = $get_order['order_no'];
                    $UOrderdb->param['invoice_data'] = $invoice_data;
                    $UOrderdb->setInvoice();
                }
            }

        }


        echo 'success';
        exit();
    }

    /**
     * 获取数电蓝票  获取版式文件地址
     */
    public function checkSdInvoice($order_no)
    {
        $serviceId = 'HQBSWJDZ';
        $api = '/invoiceEx/zpy/electric/invoice/getInvoiceUrl';
        $get_invoice = Db::name('invoice')->where('order_nos', $order_no)->field('invoice_id,fapiaohao,api_return_no')->find();
        if (!$get_invoice) {
            $this->layuiReturn('发票信息错误', 0);
        }
        $content = [];
        $content ['fphm'] = $get_invoice['fapiaohao'];
        $content ['fpqqlsh'] = $get_invoice['api_return_no'];
        $result = $this->sdsend($api, $serviceId, $content, $order_no);
        if ($result['code'] == '0') {
            // 成功
            $uploaddb = new Uploaddb ();
            $uploaddb->param ['save_path'] = $result['content']['pdfUrl'];
            $uploaddb->param ['file_name'] = time() . '.pdf';
            $uploaddb->param ['is_outlink'] = 2;
            $uploaddb->param ['type'] = 'pdf';
            $uploaddb->param ['size'] = 100;
            $get_upload = $uploaddb->ajaxSave();

            $invoice_data ['invoice_proof'] = $get_upload ['upload_id'];
            $invoicedb = new Invoicedb();
            $invoicedb->useGlobalScope(false)->where('invoice_id', $get_invoice ['invoice_id'])->update($invoice_data);

            $this->layuiReturn($result['msg'], 1);

        } else {
            $this->layuiReturn('失败，错误码：' . $result['msg'], 0);
        }
    }

    /**
     * 红字发票信息确认申请单
     */
    public function sdApplyHzInvoice($order_no)
    {
        $serviceId = 'HZXXBSC';
        $api = '/invoiceEx/zpy/electric/invoice/applyRedInformation';
        $get_invoice = Db::name('invoice')->where('order_nos', $order_no)->field('invoice_id,fapiaohao,api_return_no,invoice_money,shuie,kprq')->find();
        $content = [];
        $content['chyydm'] = '02';
        $content['hzcxje'] = -number_format(($get_invoice['invoice_money'] / 100 - $get_invoice['shuie']), 2, '.', '');
        $content['hzcxse'] = -$get_invoice['shuie'];
        $content['sqly'] = '0';
        $content['xfsh'] = $this->sd['nsrsbh'];
        $content['yfplxdm'] = '82';
        $content['ykprq'] = $get_invoice['kprq'];
        $content['yfphm'] = $get_invoice['fapiaohao'];
        $content['hzsqlsh'] = 'HC' . $order_no . '_' . date('YmdHis');
        $content['spExt']['hddz'] = "https://tailongji.dixintong.com/erp/invoiceapi/sdcallback/service_id/HZXXBSCBC/order_no/" . $order_no . ".html";
        $result = $this->sdsend($api, $serviceId, $content, $order_no);
        if ($result['code'] == '0') {

            $invoice_data ['state'] = 4;
            $invoice_data ['invoice_proof'] = '';
            $invoice_data ['api_bianhao'] = '';
            $invoice_data ['fapiaohao'] = '';

            $orderdb = new Orderdb ();
            $orderdb->useGlobalScope(false)->where('order_no', $order_no)->update([
                'invoice_state' => 1,
                'returncode' => '红冲成功',
                'invoice_time' => null,
                'is_down' => 2
            ]);
            $invoicedb = new Invoicedb();
            $invoicedb->useGlobalScope(false)->where('order_nos', $order_no)->update($invoice_data);

            $UOrderdb = new UOrderdb();
            $UOrderdb->param['order_no'] = $order_no;
            $UOrderdb->param['invoice_data'] = $invoice_data;
            $UOrderdb->setInvoice();

            $this->layuiReturn($result['msg'], 1);

        } else {
            $this->layuiReturn('失败，错误码：' . $result['msg'], 0);
        }
    }

    /**
     * 数电请求服务
     */
    protected function sdsend($api, $serviceId, $content, $order_no)
    {
        $get_token = $this->getSdToken();
        $date = (int)round(microtime(true) * 1000);
        $json_data = [];
        $json_data['serviceId'] = $serviceId;
        $json_data['dlzh'] = $this->sd['dlzh'];
        $json_data['nsrsbh'] = $this->sd['nsrsbh'];
        $json_data['content'] = $content;
        $post_data = json_encode($json_data, JSON_UNESCAPED_UNICODE);
        $post_data = str_replace('\\/', '/', $post_data);
        $md5_content = base64_encode(md5($post_data . $date . $get_token));
        $headers = [];
        $headers[] = 'Content-Type:application/json';
        $headers[] = 'Date:' . $date;
        $headers[] = 'APPID:' . $this->sd['APPID'];
        $headers[] = 'Content-MD5:' . $md5_content;


        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $this->sd['api_url'] . $api);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        // 写日志
        $log_data = [];
        $log_data['order_no'] = $order_no;
        $log_data['api'] = $api;
        $log_data['service_id'] = $serviceId;
        $log_data['content'] = $post_data;
        $log_data['result'] = $result;
        $log_data['api_date'] = date('Y-m-d H:i:s');
        $sd_invoice_logdb = new SdInvoiceLogdb();
        $sd_invoice_logdb->save($log_data);


        return json_decode($result, true);
    }


    /**
     * 臻票云请求
     * 开放平台地址；http://dev.zhenpos.com/openPlat
     * 开放平台账号：联系数族运营人员申请
     */
    public function makeInvoice($order_no, $kplx = 0, $fpqqlsh = '')
    {
        sleep(5);
        $orderdb = new Orderdb ();
        $cartdb = new Cartdb ();
        $goodsdb = new Goodsdb ();
        $array ['fyxm'] = array();
        $get_cart = $cartdb->useGlobalScope(false)->where('order_no', $order_no)->select();
        $invoicedb = new Invoicedb ();
        $get_invoice = $invoicedb->useGlobalScope(false)->where('order_nos', $order_no)->find()->toArray();
        $orderdb = new Orderdb();
        $get_order = $orderdb->where('order_no', $order_no)->find()->toArray();
        /*if ($get_invoice ['state'] == 3) {
            $this->layuiReturn('正在生成发票');
            exit ();
        }*/
        if ($get_cart) {
            $get_cart = $get_cart->toArray();
            // 下面处理商品信息
            foreach ($get_cart as $key => $val) {
                $get_goods = $goodsdb->useGlobalScope(false)->where('goods_sku', $val ['goods_sku'])->find();
                $goods ['fphxz'] = 0; // 发票行性质，0正常1折扣2被折扣
                $goods ['spmc'] = $val['product_firm'] ? $val['product_firm'] : $get_goods ['product_firm']; // 商品名称
                $goods ['spsl'] = $val ['goods_num']; // 商品数量
                $goods ['sl'] = $val['goods_keywords'] ?: $get_goods['goods_keywords']; // 税率
                //从订单金额算
                $goods ['hsze'] = $val ['goods_price'] * $val ['goods_num'];
                $goods ['je'] = number_format($goods ['hsze'] / (1 + $goods ['sl']), 2, '.', ''); // 总价
                $goods ['se'] = number_format($goods ['hsze'] - $goods ['je'], 2, '.', '');//税额
                $goods ['dj'] = $goods ['je'] / $val ['goods_num']; // 单价
                /*
                //从单价算
                $goods ['dj'] = $val ['goods_price'] / (1 + $get_goods ['goods_keywords']); // 单价
                $goods ['je'] = number_format($goods ['dj'] * $goods ['spsl'], 2, '.', ''); // 总价
                $goods ['se'] = number_format($goods ['je'] * $goods ['sl'], 2, '.', '');//税额
                */
                $goods ['hsbz'] = 1;
                $goods ['dw'] = $val['goods_unit'] ? $val['goods_unit'] : $get_goods ['goods_unit'];
                $goods ['ggxh'] = $val['invoice_model'] ?: $get_goods['invoice_model'];
//halt($goods);
                if ($kplx == 1) {
                    $goods ['je'] = 0 - $goods ['je'];
                    $goods ['se'] = 0 - $goods ['se'];
                    $goods ['spsl'] = 0 - $goods ['spsl'];
                }
                $goods['spbm'] = $val['shuiwu_id'] ?: $get_goods['shuiwu_id'];
                array_push($array ['fyxm'], $goods);
            }
            if (!$get_invoice['api_bianhao']) {
              $array ['fpqqlsh'] = $get_order ['out_order_no'] . '_' . date('YmdHis') . rand(1000, 9999);
            } else {
                $array ['fpqqlsh'] = $get_invoice['api_bianhao'];
            }
            if ($kplx == 1) {
                // 红冲
               $array ['fpqqlsh'] = 'FPDTL' . date ( 'YmdHis' ) . rand ( 1000, 9999 );
            }
            
           // $array ['fpqqlsh'] = 'FPDTL' . $order_no;
            $array ['shnsrsbh'] = $this->shuihao; // 纳税人识别号
            $array ['jsbh'] = $this->shuihao . '~~' . $this->bianhao; // 机器编号
           // $array ['xhdwdzdh'] = $this->dizhi;
           // $array ['xhdwyhzh'] = $this->yinhang;
            $array ['fplxdm'] = '026'; // '发票类型代码 026电子普票，028电子专票 025普通卷式发票 007增值税普票 004增值税专票';
            $array ['kplx'] = $kplx; // 0正数票开具 1负数票开具
            $array ['yhlx'] = 0; // 0 接口开票
            // 开始处理发票信息

            $array ['ghdwsbh'] = $get_invoice ['invoice_duty'] ?: '';
            $array ['ghdwmc'] = $get_invoice ['invoice_title'];
            $array ['ghdwdzdh'] = $get_invoice ['invoice_addr'] . ' ' . $get_invoice ['invoice_tel'];
            $array ['ghdwyhzh'] = $get_invoice ['invoice_bank'] . ' ' . $get_invoice ['invoice_account'];
            $array ['bz'] = $get_invoice ['invoice_beizhu'];
            //  halt($array);
            // $array ['skr'] = '收款人';
           // $array ['kpr'] = $this->kaipiaoren;
            if ($kplx == 1) {
                // 红冲
                $array ['yfpdm'] = $get_invoice ['fapiaodaima'];
                $array ['yfphm'] = $get_invoice ['fapiaohao'];
            }
            // $array ['sprsjh'] = '收票人手机号';
            $array ['notify_url'] = 'https://tailongji.dixintong.com/erp/invoiceapi/callback.html';
            $xml_arr ['body'] ['input'] = $array;
            $base_str = '<?xml version="1.0" encoding="utf-8"?><business id="FPKJ"></business>';
            $body_xml = new \SimpleXMLElement ($base_str);
            $this->arrToXml($xml_arr, $body_xml);
            $body_xml = $body_xml->asXML();
            $xml = new \SimpleXMLElement ($this->getToken());
            $access_token = $xml->body->access_token;
            $date = time();
            $contentCurrent = base64_encode(md5($body_xml . $date . $access_token));
            $uri = 'business';
            $url = $this->baseUrl . $uri;
            $client = new Client ();
            $response = $client->post($url, [
                'headers' => [
                    'Content-Type' => 'application/xml',
                    'APPID' => $this->appid,
                    'Date' => $date,
                    'Content-MD5' => $contentCurrent
                ],
                'body' => ($body_xml)
            ]);
            $response_content = $response->getBody()->getContents();
            $return_xml = new \SimpleXMLElement ($response_content);
            $code = $return_xml->body->returncode;
            $msg = $return_xml->body->returnmsg;
            if ($code == 0) {
                $db = new Db ();
                if ($kplx == 0) {
                    $invoice_data ['state'] = 3;
                    $invoice_data ['api_bianhao'] = $array ['fpqqlsh'];
                    $invoice_data ['api_type'] = $array ['fplxdm'];
                    $invoice_data ['api_date'] = date('Y-m', time());

                } else {
                    // 发票红冲
                    $invoice_data ['state'] = 4;
                    $invoice_data ['invoice_proof'] = '';
                    $invoice_data ['api_bianhao'] = '';
                    $invoice_data ['fapiaohao'] = '';
                    $orderdb = new Orderdb ();
                    $orderdb->useGlobalScope(false)->where('order_no', $order_no)->update([
                        'invoice_state' => 1,
                        'returncode' => '红冲成功',
                        'invoice_time' => null,
                        'is_down' => 2
                    ]);
                }
                $invoicedb->useGlobalScope(false)->where('order_nos', $order_no)->update($invoice_data);

                $UOrderdb = new UOrderdb();
                $UOrderdb->param['order_no'] = $order_no;
                $UOrderdb->param['invoice_data'] = $invoice_data;
                $UOrderdb->setInvoice();
                Cache::clear('order');
                Cache::clear('invoice');
                $this->layuiReturn('提交成功，请稍后查询', 1);
            } else {
                $this->layuiReturn('失败，错误码：' . $msg, 1);
            }
        }
    }


    public function getInvoicePath($order_no, $upload_id)
    {
        $date = time();
        $invoicedb = new Invoicedb();
        $get_invoice = $invoicedb->where('order_nos', $order_no)->find();
        $uri = 'business';
        $url = $this->baseUrl . $uri;
        $array = [];
        $array ['nsrsbh'] = $this->shuihao; // 纳税人识别号
        $array ['fplxdm'] = '026';
        $array['cxfs'] = 1;
        $array['cxtj'] = $get_invoice['api_bianhao'];
        $xml_arr ['body'] ['input'] = $array;
        $base_str = '<?xml version="1.0" encoding="utf-8"?><business id="FPCX"></business>';
        $body_xml = new \SimpleXMLElement ($base_str);
        $this->arrToXml($xml_arr, $body_xml);
        $body_xml = $body_xml->asXML();
        $xml = new \SimpleXMLElement ($this->getToken());
        $access_token = $xml->body->access_token;
        $contentCurrent = base64_encode(md5($body_xml . $date . $access_token));
        $uri = 'business';
        $url = $this->baseUrl . $uri;
        $client = new Client ();
        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/xml',
                'APPID' => $this->appid,
                'Date' => $date,
                'Content-MD5' => $contentCurrent
            ],
            'body' => ($body_xml)
        ]);
        $response_content = $response->getBody()->getContents();
        $return_xml = new \SimpleXMLElement ($response_content);
        $code = $return_xml->body->returncode;
        $data = $return_xml->body->returndata->kpxx;
        if ($code == 0) {
            // 如果没有数据 则赋值
            if (!$get_invoice['invoice_proof']) {
                $uploaddb = new Uploaddb ();
                $get_upload = $uploaddb->find($upload_id);
                $get_upload->save(['save_path' => (string)$data->url]);
            }
        }
    }

    public function checkInvoice($order_no)
    {
        $date = time();
        $invoicedb = new Invoicedb();
        $get_invoice = $invoicedb->where('order_nos', $order_no)->find();
        $uri = 'business';
        $url = $this->baseUrl . $uri;
        $array = [];
        $array ['nsrsbh'] = $this->shuihao; // 纳税人识别号
        $array ['fplxdm'] = '026';
        $array['cxfs'] = 1;
        $array['cxtj'] = $get_invoice['api_bianhao'];
        $xml_arr ['body'] ['input'] = $array;
        $base_str = '<?xml version="1.0" encoding="utf-8"?><business id="FPCX"></business>';
        $body_xml = new \SimpleXMLElement ($base_str);
        $this->arrToXml($xml_arr, $body_xml);
        $body_xml = $body_xml->asXML();
        $xml = new \SimpleXMLElement ($this->getToken());
        $access_token = $xml->body->access_token;
        $contentCurrent = base64_encode(md5($body_xml . $date . $access_token));
        $uri = 'business';
        $url = $this->baseUrl . $uri;
        $client = new Client ();
        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/xml',
                'APPID' => $this->appid,
                'Date' => $date,
                'Content-MD5' => $contentCurrent
            ],
            'body' => ($body_xml)
        ]);
        $response_content = $response->getBody()->getContents();
        $return_xml = new \SimpleXMLElement ($response_content);
        $code = $return_xml->body->returncode;
        $data = $return_xml->body->returndata->kpxx;
        if ($code == 0) {
            // 如果没有数据 则赋值 暂时屏蔽
            //if (!$get_invoice['invoice_proof']) {
            $uploaddb = new Uploaddb ();
            $uploaddb->param ['save_path'] = (string)$data->url;
            $uploaddb->param ['file_name'] = time() . 'pdf';
            $uploaddb->param ['is_outlink'] = 2;
            $uploaddb->param ['type'] = 'pdf';
            $uploaddb->param ['size'] = 100;
            $get_upload = $uploaddb->ajaxSave();
            $get_invoice->save([
                'api_return_no' => (string)$data->szfpqqlsh,
                'fapiaohao' => (string)$data->fphm,
                'fapiaodaima' => (string)$data->fpdm,
                'invoice_proof' => $get_upload ['upload_id']
            ]);
            $orderdb = new Orderdb();
            $get_order = $orderdb->where('order_no', $order_no)->find();
            if ($get_order) {
                $get_order->save(['returncode' => '成功']);
            }
            //}
            $this->layuiReturn('查询成功', 1);
        } else {
            $this->error('查询失败');
        }

    }

    // 数据回调
    public function callback()
    {
        $fileContent = file_get_contents("php://input");

        $xml = new \SimpleXMLElement ($fileContent);
        $result_msg = $xml->body->returnmsg;
        $invoicedb = new Invoicedb ();
        $chk_invoice = $invoicedb->useGlobalScope(false)->where('api_bianhao', $xml->body->fpqqlsh)->find();
        if ($xml->body->returncode != 0) {
            $orderdb = new Orderdb ();
            $orderdb->useGlobalScope(false)->where('order_no', $chk_invoice ['order_nos'])->update([
                'invoice_state' => 1,
                'returncode' => $result_msg
            ]);
            echo 'success';
            exit();
        }
        if ($chk_invoice) {
            $chk_invoice = $chk_invoice->toArray();
            if ($chk_invoice ['state'] == 3 || $chk_invoice['state'] == 2) {
                $uploaddb = new Uploaddb ();
                $uploaddb->param ['save_path'] = $xml->body->returndata->kpxx->url;
                $uploaddb->param ['file_name'] = time() . 'pdf';
                $uploaddb->param ['is_outlink'] = 2;
                $uploaddb->param ['type'] = 'pdf';
                $uploaddb->param ['size'] = 100;
                $get_upload = $uploaddb->ajaxSave();
                $save_data ['api_return_no'] = $xml->body->szfpqqlsh;
                $save_data ['fapiaohao'] = $xml->body->returndata->kpxx->fphm;
                $save_data ['fapiaodaima'] = $xml->body->returndata->kpxx->fpdm;
                $save_data ['state'] = 2;
                $save_data ['invoice_time'] = time();
                $save_data ['invoice_proof'] = $get_upload ['upload_id'];
                $invoicedb->useGlobalScope(false)->where('invoice_id', $chk_invoice ['invoice_id'])->update($save_data);
                $orderdb = new Orderdb ();
                $orderdb->useGlobalScope(false)->where('order_no', $chk_invoice ['order_nos'])->update([

                    'returncode' => $result_msg
                ]);
            } else {
                $orderdb = new Orderdb ();
                $orderdb->useGlobalScope(false)->where('order_no', $chk_invoice ['order_nos'])->update([
                    'invoice_state' => 1,
                    'returncode' => $result_msg
                ]);
            }
            Cache::clear('order');
            Cache::clear('invoice');
        }
        // 调试代码
        $post_data ['post_json'] = $fileContent;
        $post_data ['post_url'] = 'invoiceapi';
        $post_data ['create_time'] = time();
        $postdatadb = new Postdatadb ();
        $postdatadb->param = $post_data;
        $postdatadb->ajaxSave();
        // 调试代码结束
        echo 'success';
    }

    protected function ajaxReturn($data, $json_option = 0)
    {
        header('Content-Type:application/json; charset=utf-8');
        exit (json_encode($data, $json_option));
    }

    protected function layuiReturn($data, $count = 0, $msg = '', $code = 0)
    {
        $return ['data'] = $data;
        $return ['count'] = $count;
        $return ['msg'] = $msg;
        $return ['code'] = $code;
        $this->ajaxReturn($return);
    }

    /**
     * 获取accessToken
     *
     * @return string
     */
    private function getToken()
    {
        /**
         * 如果appId appSecret大小写没有拼对，会返回“The given data failed to pass validation.”
         */
        $message ['appId'] = $this->appid;
        $message ['appSecret'] = $this->appSecret;
        $uri = 'token';
        $url = $this->baseUrl . $uri;
        $client = new Client ();
        $body = json_encode($message, JSON_UNESCAPED_UNICODE);
        $response = $client->post($url, [
            'headers' => [
                'Content-Type' => 'application/json'
            ],
            'body' => ($body)
        ]);
        $content = $response->getBody()->getContents();
        return $content;
    }

    // arrToXml
    private function arrToXml($array, &$xml_user_info)
    {
        foreach ($array as $key => $value) {
            if (is_array($value)) {
                if (!is_numeric($key)) {
                    $subnode = $xml_user_info->addChild("$key");
                    if ($key == 'fyxm') {
                        $subnode->addAttribute('count', count($array ['fyxm']));
                    }
                    $this->arrToXml($value, $subnode);
                } else {
                    $subnode = $xml_user_info->addChild("group");
                    $subnode->addAttribute('xh', $key + 1);
                    $this->arrToXml($value, $subnode);
                }
            } else {
                $xml_user_info->addChild("$key", htmlspecialchars("$value"));
            }
        }
    }
}